package top.pengdong.dachuang.main.point;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import top.pengdong.common.utils.ResultCode;
import top.pengdong.common.utils.ResultResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: 当还没登陆或者token失效访问接口时候，自定义返回结果
 * @projectName: RealHole
 * @see: com.pengshi.realhole.point
 * @author: pc
 * @createTime: 2022/2/11 21:59
 * @version: 1.0
 */
@Component
public class RestAuthorizationEntryPoint implements AuthenticationEntryPoint {
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		out.write(new ObjectMapper().writeValueAsString(ResultResponse.fail(ResultCode.USER_NOT_EXIST)));
		out.flush();
		out.close();
	}
}
